﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ANZ_AIM_BLL;
using ANZ_AIM_FRAMEWORK;
using ANZ_AIM_BLL.Model;
using ANZ_AIM_GUI.Utils;
using System.Text.RegularExpressions;
using System.IO;
using log4net;

namespace ANZ_AIM_GUI
{
    public partial class frmSaleChangeUpload : Form
    {
        //log4net
        private static readonly ILog logger = LogManager.GetLogger(typeof(frmSaleChangeUpload));

        AppParam param = AppParam.Instance;

        public List<SaleChangeRequest> saleChangeRequestList = new List<SaleChangeRequest>();
        public frmSaleChangeUpload()
        {
            InitializeComponent();

            try
            {
                LoadData();
            }
            catch (Exception ex) { throw ex; }
        }
        private void LoadData()
        {
            try
            {
                BatchFileChangeUploadBLL batchFileChangeUploadBl = new BatchFileChangeUploadBLL();
                DataTable dt = batchFileChangeUploadBl.GetBatchFileByStatus(Constant.NEED_TO_VERIFY);

                foreach (DataRow item in dt.Rows)
                {
                    item["Status"] = Constant.BatchStatusMap[item["Status"].ToString()];
                }

                dgvData.DataSource = null;
                dgvData.Columns.Clear();
                dgvData.DataSource = dt;

                dgvData.Columns["BatchFileChangeID"].HeaderText = "Batch File Change ID";
                dgvData.Columns["BatchFileChangeID"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Columns["FileName"].HeaderText = "File Name";
                dgvData.Columns["FileName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvData.Columns["TotalRecord"].HeaderText = "Total Record";
                dgvData.Columns["TotalRecord"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Columns["TotalRecord"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgvData.Columns["CreatedDate"].HeaderText = "Created Date";
                dgvData.Columns["CreatedDate"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Columns["Status"].HeaderText = "Status";
                dgvData.Columns["Status"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                this.dgvData.Sort(this.dgvData.Columns["CreatedDate"], ListSortDirection.Descending);
            }
            catch (Exception ex) { throw ex; }
        }

        //Check max file size when upload
        private bool checkFileSizeUpload(string filePath)
        {
            try
            {
                ConfigurationBLL configurationBLL = new ConfigurationBLL();
                Configuration configuration = configurationBLL.GetByKey(Configuration.MAX_FILE_SIZE_UPLOAD);
                string maxFileSize = configuration.ConfigValue;
                FileInfo fileInfo = new FileInfo(filePath);
                if (fileInfo.Length / 1024 > Convert.ToDouble(maxFileSize))
                {
                    MessageBox.Show("The file size is greater than Maximum, please select another file.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                return true;
            }
            catch (Exception ex) { throw ex; }
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ExcelDialog = new OpenFileDialog();
                ExcelDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
                ExcelDialog.InitialDirectory = param.PathFile;
                ExcelDialog.Title = "Select your file excel";
                if (ExcelDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtFileName.Text = ExcelDialog.FileName;
                    txtFileName.ReadOnly = true;

                    var lastPath = txtFileName.Text;
                    lastPath = lastPath.Substring(0, lastPath.LastIndexOf("\\"));
                    if (param.PathFile != lastPath)
                        param.PathFile = lastPath;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            int IDFileBatchUpload = 0;
            var msg = String.Empty;
            try
            {
                if (string.IsNullOrEmpty(txtFileName.Text.Trim()))
                {
                    MessageBox.Show("File Name cannot be empty.", Constant.SYS_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtFileName.Focus();
                    return;
                }

                //Check file size       
                if (checkFileSizeUpload(txtFileName.Text.Trim()) == false)
                    return;

                //clear list when upload new file
                saleChangeRequestList.Clear();

                //insert BatchFileChangeUpload DB                
                BatchFileChangeUploadBLL batchFileChangeBll = new BatchFileChangeUploadBLL();
                string[] s = txtFileName.Text.Trim().Split('\\');
                batchFileChangeBll.Save(new BatchFileChangeUpload() { CreatedDate = MiscHelper.DateTimeToShort(DateTime.Now), FileName = s[s.Length - 1], Status = Constant.NEED_TO_VERIFY }, ref IDFileBatchUpload);

                //bind datarow to list 
                DataTable dtData = NPOIHelper.ImportExceltoDt(txtFileName.Text.Trim(), 0, 1);
                foreach (DataRow dr in dtData.Rows)
                {
                    PackObject(dr, IDFileBatchUpload.ToString());
                }

                //insert Sale ChangeRequest DB
                SaleChangeRequestBLL saleChangeRequestBll = new SaleChangeRequestBLL();
                saleChangeRequestBll.Save(saleChangeRequestList);

                MessageBox.Show("Upload Successfully.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);

                //load lai du lieu
                LoadData();

                msg = String.Format("{0}, batchFileID: {1}", Constant.SYS_MSG_SALE_UPLOAD, txtFileName.Text.Trim());
            }
            catch (Exception ex)
            {
                BatchFileChangeUploadBLL batchFileChangeBll = new BatchFileChangeUploadBLL();
                batchFileChangeBll.Delete(IDFileBatchUpload.ToString());
                MessageBox.Show("The imported file is not right.");
                logger.Error(ex.Message + " - " + ex.StackTrace);
                return;
            }

            try
            {
                if (!String.IsNullOrEmpty(msg))
                {
                    LogBLL logBll = new LogBLL();
                    logBll.Description = msg;
                    logBll.Log(this.FindForm(), param.UserName);
                }
            }
            catch { }
        }

        private void PackObject(DataRow drData, string batchFileChangeID)
        {
            try
            {
                SaleChangeRequest saleChangeRequest = new SaleChangeRequest();
                saleChangeRequest.ProfileID = drData["Profile ID"].ToString();
                saleChangeRequest.BatchFile = drData["Batch File"].ToString();
                saleChangeRequest.FieldChange = drData["Field Change"].ToString();
                saleChangeRequest.OldValue = drData["Old Value"].ToString();
                saleChangeRequest.NewValue = drData["New Value"].ToString();
                saleChangeRequest.BatchFileChangeID = batchFileChangeID;

                saleChangeRequestList.Add(saleChangeRequest);
            }
            catch (Exception ex) { throw ex; }
        }

        private void dgvData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                int selectedRowCount = dgvData.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvData.SelectedRows[0].DataBoundItem).Row;
                    frmDataChangeUpload frmDateChangeUpload = new frmDataChangeUpload(dr[0].ToString());
                    frmDateChangeUpload.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }
    }
}
